package com.wutongyu.mannyburger;

import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.DiffUtil;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import java.util.ArrayList;
import java.util.List;

public class AllOrderActivity extends AppCompatActivity {

    private RecyclerView orderRecyclerView;
    private Button copyButton;
    private ImageView backButton;
    private OrderAdapter orderAdapter;
    private OrderDatabaseHelper dbHelper;
    private List<Order> orderList;
    private View emptyView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_all_order);

        // 绑定控件
        orderRecyclerView = findViewById(R.id.orderRecyclerView);
        copyButton = findViewById(R.id.copyButton);
        backButton = findViewById(R.id.backButton);
        emptyView = findViewById(R.id.emptyView);

        // 设置返回按钮点击事件
        backButton.setOnClickListener(v -> {
            finish(); // 关闭当前Activity，返回上一级
        });

        // 初始化数据库
        dbHelper = new OrderDatabaseHelper(this);
        
        // 初始化列表控件
        orderRecyclerView.setLayoutManager(new LinearLayoutManager(this));
        orderList = new ArrayList<>(); // 先初始化一个空列表
        orderAdapter = new OrderAdapter(orderList);
        orderRecyclerView.setAdapter(orderAdapter);
        
        // 加载订单数据
        loadOrders();

        // 按钮监听控件
        copyButton.setOnClickListener(v -> {
            if (!orderList.isEmpty()) {
                Order lastOrder = orderList.get(0); // 获取最新订单（第一个）
                
                // 创建Intent前往结算页面
                Intent intent = new Intent(AllOrderActivity.this, OrderActivity.class);
                
                // 传递订单信息
                intent.putExtra("order_details", lastOrder.getItems());
                intent.putExtra("total_price", lastOrder.getTotalPrice());
                
                // 可选：传递备注信息
                if (lastOrder.getNote() != null && !lastOrder.getNote().isEmpty()) {
                    intent.putExtra("note", lastOrder.getNote());
                }
                
                // 启动结算页面
                startActivity(intent);
            } else {
                Toast.makeText(AllOrderActivity.this, "没有可复制的订单", Toast.LENGTH_SHORT).show();
            }
        });
    }

    // 加载所有订单
    private void loadOrders() {
        List<Order> newOrders = dbHelper.getAllOrders();
        orderAdapter.updateOrders(newOrders);
        orderList = newOrders;
        
        // 更新空状态视图
        if (orderList.isEmpty()) {
            emptyView.setVisibility(View.VISIBLE);
            orderRecyclerView.setVisibility(View.GONE);
        } else {
            emptyView.setVisibility(View.GONE);
            orderRecyclerView.setVisibility(View.VISIBLE);
        }
    }

    // 订单列表适配器
    static class OrderAdapter extends RecyclerView.Adapter<OrderAdapter.OrderViewHolder> {
        private List<Order> orderList;

        public OrderAdapter(List<Order> orderList) {
            this.orderList = new ArrayList<>(orderList);
        }

        public void updateOrders(List<Order> newOrders) {
            // 使用DiffUtil计算列表差异并优化更新
            OrderDiffCallback diffCallback = new OrderDiffCallback(this.orderList, newOrders);
            DiffUtil.DiffResult diffResult = DiffUtil.calculateDiff(diffCallback);
            
            this.orderList.clear();
            this.orderList.addAll(newOrders);
            diffResult.dispatchUpdatesTo(this);
        }

        @NonNull
        @Override
        public OrderViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
            View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_order, parent, false);
            return new OrderViewHolder(view);
        }

        @Override
        public void onBindViewHolder(@NonNull OrderViewHolder holder, int position) {
            Order order = orderList.get(position);
            holder.itemsTextView.setText(order.getItems());
            holder.noteTextView.setText("备注: " + order.getNote());
            holder.totalPriceTextView.setText("总价: ¥" + order.getTotalPrice());
            
            // 显示订单时间
            String timestamp = order.getTimestamp();
            if (timestamp != null && !timestamp.isEmpty()) {
                holder.orderTimeTextView.setText("订单时间: " + timestamp);
            } else {
                holder.orderTimeTextView.setText("订单时间: 未知");
            }
            
            // 显示送餐方式
            String deliveryType = order.getDeliveryType();
            if (deliveryType == null || deliveryType.isEmpty()) {
                deliveryType = "自提"; // 默认为自提
            }
            holder.deliveryTypeTextView.setText(deliveryType);
            
            // 显示送餐地址
            String deliveryAddress = order.getDeliveryAddress();
            if (deliveryType.equals("外卖") && !TextUtils.isEmpty(deliveryAddress)) {
                holder.deliveryAddressTextView.setText(deliveryAddress);
                holder.deliveryAddressTextView.setVisibility(View.VISIBLE);
            } else {
                holder.deliveryAddressTextView.setVisibility(View.GONE);
            }
            
            // 设置点击事件
            holder.itemView.setOnClickListener(v -> {
                // 这里可以添加订单详情查看逻辑
                Toast.makeText(v.getContext(), "订单ID: " + order.getId(), Toast.LENGTH_SHORT).show();
            });
        }

        @Override
        public int getItemCount() {
            return orderList.size();
        }

        static class OrderViewHolder extends RecyclerView.ViewHolder {
            TextView itemsTextView;
            TextView noteTextView;
            TextView totalPriceTextView;
            TextView orderTimeTextView;
            TextView deliveryTypeTextView;
            TextView deliveryAddressTextView;

            public OrderViewHolder(@NonNull View itemView) {
                super(itemView);
                itemsTextView = itemView.findViewById(R.id.itemsTextView);
                noteTextView = itemView.findViewById(R.id.noteTextView);
                totalPriceTextView = itemView.findViewById(R.id.totalPriceTextView);
                orderTimeTextView = itemView.findViewById(R.id.orderTimeTextView);
                deliveryTypeTextView = itemView.findViewById(R.id.deliveryTypeTextView);
                deliveryAddressTextView = itemView.findViewById(R.id.deliveryAddressTextView);
            }
        }
    }
    
    // DiffUtil回调类用于高效更新RecyclerView
    static class OrderDiffCallback extends DiffUtil.Callback {
        private final List<Order> oldOrders;
        private final List<Order> newOrders;

        public OrderDiffCallback(List<Order> oldOrders, List<Order> newOrders) {
            this.oldOrders = oldOrders;
            this.newOrders = newOrders;
        }

        @Override
        public int getOldListSize() {
            return oldOrders.size();
        }

        @Override
        public int getNewListSize() {
            return newOrders.size();
        }

        @Override
        public boolean areItemsTheSame(int oldItemPosition, int newItemPosition) {
            return oldOrders.get(oldItemPosition).getId() == newOrders.get(newItemPosition).getId();
        }

        @Override
        public boolean areContentsTheSame(int oldItemPosition, int newItemPosition) {
            Order oldOrder = oldOrders.get(oldItemPosition);
            Order newOrder = newOrders.get(newItemPosition);
            return oldOrder.getId() == newOrder.getId() &&
                    oldOrder.getTotalPrice() == newOrder.getTotalPrice() &&
                    (oldOrder.getItems() != null && oldOrder.getItems().equals(newOrder.getItems())) &&
                    (oldOrder.getNote() != null && oldOrder.getNote().equals(newOrder.getNote())) &&
                    (oldOrder.getTimestamp() != null && oldOrder.getTimestamp().equals(newOrder.getTimestamp())) &&
                    (oldOrder.getDeliveryType() != null && oldOrder.getDeliveryType().equals(newOrder.getDeliveryType())) &&
                    ((oldOrder.getDeliveryAddress() == null && newOrder.getDeliveryAddress() == null) ||
                            (oldOrder.getDeliveryAddress() != null && oldOrder.getDeliveryAddress().equals(newOrder.getDeliveryAddress())));
        }
    }
}